<?php

namespace App\Admin\Controllers\Financial;

use App\Admin\Models\Financial\FinancialMoneylog;
use App\Common\Services\Store\Common as StoreCommon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use App\Admin\Validate\Financial\FinancialMoneylog as ValidateFinancialFinancialMoneylog;
use App\Common\Services\CommonExcelExport;
use App\Common\Services\CommonExcelExportWithTitle;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;
class FinancialMoneylogController extends Controller
{
    /**
     * 获取列表
     */
    public function getlist(Request $request)
    {
        $type=$request->type;
        if(!in_array($type,[1,2])){
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $list = FinancialMoneylog::getList($request,$type);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }
    public function getinfo(Request $request)
    {
        $type=$request->type;
        if(!in_array($type,[1,2])){
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $id = $request->id ?? 0;
        $info = FinancialMoneylog::where(['id' => $id,'is_del'=>1,'type'=>$type])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }

    public function dopostadd(Request $request)
    {
        $req_data = $request->only(['type','inout_type','abstract','receipt_type', 'log_date', 'pay_type_id', 'receipt_no', 'subject_id', 'income_money','expenditure_money','residue_money','remark']);

        $Validate = new ValidateFinancialFinancialMoneylog;
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }


        $data = $req_data;
        $data['log_date']=date('Y-m-d',strtotime($data['log_date']));
        $data['create_at'] = time();
        $data['update_at'] = time();
        FinancialMoneylog::create($data);
        return response()->json(['code' => '000', 'msg' => '新增日记账成功']);
    }

    public function dopostedit(Request $request)
    {
        $req_data = $request->only(['id','type','abstract', 'log_date', 'pay_type_id', 'receipt_no', 'subject_id', 'income_money','expenditure_money','residue_money','remark','inout_type', 'receipt_type']);

        $Validate = new ValidateFinancialFinancialMoneylog('edit');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }



        $info = FinancialMoneylog::where(['id'=>$req_data['id'],'is_del'=>1,'type'=>$req_data['type']])->first();
        if(!$info){
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }



        $data = $req_data;
        $data['log_date']=date('Y-m-d',strtotime($data['log_date']));
        $data['update_at'] = time();
        FinancialMoneylog::where(['id'=>$req_data['id'],'is_del'=>1])->update($data);
        return response()->json(['code' => '000', 'msg' => '编辑日记账成功']);
    }

    public function dopostdel(Request $request)
    {
        $type=$request->type;
        if(!in_array($type,[1,2])){
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $id=$request->id ?? 0;
        $info = FinancialMoneylog::where(['id'=>$id,'is_del'=>1,'type'=>$type])->first();
        if(!$info){
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        FinancialMoneylog::where(['id'=>$id])->update(['is_del'=>2,'del_at'=>time()]);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }


    public function getlastmoneylog(Request $request){
        $type=$request->type;
        if(!in_array($type,[1,2])){
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $last_moneylog=FinancialMoneylog::where(['type'=>$type,'is_del'=>1])->orderBy('id','desc')->first();
        $last_moneylog_residue_money=$last_moneylog?$last_moneylog->residue_money:0;

        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['last_moneylog_residue_money'=>$last_moneylog_residue_money]]);
    }

    public function getmoneylogcountbyday(Request $request){
        $type=$request->type;
        if(!in_array($type,[1,2])){
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $receipt_type=intval($request->receipt_type);
        //是否返回receipt_no
        $data=$this->getmoneylogcount($type,$receipt_type);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' =>$data]);
    }

    protected function getmoneylogcount($type,$receipt_type){
        $log_date_s=date('Y-m').'-01';
        $count=FinancialMoneylog::where([['type',$type],['log_date','>=',$log_date_s],['inout_type','>',0]])->count();
        $count+=1;
        return ['count'=>$count,'no'=>date('n').'-'.$count.'#'];
    }



    public function doexport(Request $request)
    {
        $subject_name_arr=['-1'=>'销售收入','-2'=>'销售费用','-3'=>'销售费用-商品维修费','-4'=>'销售费用-广告费和业务宣传费','-5'=>'财务费用-手续费'];
        $type=$request->type;
        if(!in_array($type,[1,2])){
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $list = FinancialMoneylog::getList($request,$type)['list'];
        $exceldata = [];
        $row = [
            ['log_date'=>($type==1?'现金':'银行').'日记账'],
            [
                'log_date' => '日期',
                'receipt_no' => '收据号',
                'abstract' => '摘要',
                'subject_name' => '科目',
                'income_money' => '收入金额',
                'expenditure_money' => '支出金额',
                'residue_money' => '余额',
                'remark' => '备注',
            ]
        ];
        foreach ($list as $val) {
            if($val['inout_type']==0){
                $exceldata[] = [
                    'log_date' => '',
                    'receipt_no' => '',
                    'abstract' => $val['abstract'],
                    'subject_name' => '',
                    'income_money' => $val['income_money']/100,
                    'expenditure_money' => $val['expenditure_money']/100,
                    'residue_money' => $val['residue_money']/100,
                    'remark' => '',
                ];
            }else{
                $exceldata[] = [
                    'log_date' => $val['log_date'],
                    'receipt_no' => $val['receipt_no'],
                    'abstract' => $val['abstract'],
                    'subject_name' => $val['subject_id']<0?$subject_name_arr[$val['subject_id']]:($val['subjectinfo']?$val['subjectinfo']['subject_name']:''),
                    'income_money' => $val['income_money']/100,
                    'expenditure_money' => $val['expenditure_money']/100,
                    'residue_money' => $val['residue_money']/100,
                    'remark' => $val['remark'],
                ];
            }

        }

        $filename = ($type==1?'现金':'银行').'日记账信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata,[]), $filename);
    }

    /**
     * 日记账数据修改
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateMoneyLog(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required',
            'income_money' => 'sometimes',
            'expenditure_money' => 'sometimes',
            'abstract' => 'sometimes'
        ], [
            'id.required' => 'ID必填',
        ]);

        if ($validator->fails()) {
            $msg = $validator->errors()->first();
            return response()->json(['code' => '001', 'msg' => $msg]);
        }
        $params = $validator->validated();

        $data = [];

        $abstract = $params['abstract'] ?? '';
        if (isset($params['income_money'])) {
            $data['income_money'] = $params['income_money'];
        }
        if (isset($params['expenditure_money'])) {
            $data['expenditure_money'] = $params['expenditure_money'];
        }

        if (!empty($abstract)) {
            $data['abstract'] = $abstract;
        }
        $log = FinancialMoneylog::query()
            ->where(['id' => $params['id'], 'is_del' => 1])
            ->first();
        if (empty($log)) {
            return response()->json(['code' => '001', 'msg' => '数据不存在无法修改']);
        }

        $log = $log->toArray();

        $previousId = FinancialMoneylog::query()
            ->where(['is_del' => 1,'type'=>$log['type']])
            ->where('id','<',$params['id'])
            ->max('id');

        $previous =FinancialMoneylog::query()
            ->where(['is_del' => 1,'type'=>$log['type'],'id'=>$previousId])
            ->first();
        $previous =empty($previous)?[]:$previous->toArray();

        $firstDayOfMonth = date('Y-m-01');
        $lastDayOfMonth = date('Y-m-t');

        $logDate = strtotime($log['log_date']);
        $firstDayOfMonth = strtotime($firstDayOfMonth);
        $lastDayOfMonth = strtotime($lastDayOfMonth);

        if ($logDate > $lastDayOfMonth || $logDate < $firstDayOfMonth) {
            return response()->json(['code' => '001', 'msg' => '只能修改当月的数据']);
        }
        if (!empty($data['income_money']) && !empty($params['expenditure_money'])) {
            return response()->json(['code' => '001', 'msg' => '收入和支出只能编辑一个']);
        }

        $residue_money = ($previous['residue_money']??0)+ ($data['income_money'] ?? $log['income_money']) - ($data['expenditure_money'] ?? $log['expenditure_money']);

        if (!empty($data)) {
            //先不进行核算只修改数据
            FinancialMoneylog::query()
                ->where(['id' => $params['id'], 'is_del' => 1])
                ->update($data);
        }

        if (!empty($data['income_money']) || !empty($params['expenditure_money'])) {
            //需要重新计算当月的值
            $logList = FinancialMoneylog::query()
                ->where(['is_del' => 1,'type'=>$log['type']])
                ->where('inout_type','>',0)
                ->where('id', '>=', $log['id'])
                ->get()
                ->toArray();
            $total=0;
            foreach ($logList as $key=>&$item) {
                $item['residue_money'] = $residue_money;

                if ($key>=1) {
                    $nextMoney = $residue_money;
                    if($total==0){
                        $total+= $nextMoney + $item['income_money'] - $item['expenditure_money'];
                    }else{
                        // echo $total.'--'.$item['income_money'].'--'.$item['expenditure_money'].'/';
                        $total= $total + $item['income_money'] - $item['expenditure_money'];
                    }

                    $item['residue_money']=$total;
                }
            }

            foreach ($logList as $val){
                FinancialMoneylog::query()
                    ->where('id', $val['id'])
                    ->update(['residue_money'=>$val['residue_money']]);
            }

        }
        return response()->json(['code' => '000', 'msg' => '修改成功']);
    }
}
